$(function () {
    //点击登录弹出登录页面
    $("#btnLogin").click(function () {
        $('#login-index').css('display', 'block')
        $('#register-index').css('display', 'none')
        $(".auth-body-warp").show();
    })
    //点击注册弹出注册页面
    $("#btnRegister").click(function () {
        $('#change_login').removeClass('pitch-bg')
        $('#change_register').addClass('pitch-bg')
        $('#login-index').css('display', 'none')
        $('#register-index').css('display', 'block')
        $(".auth-body-warp").show();
    })

    //登录验证码
    $("#gainCode").click(function () {
        var re = /^1[345678]\d{9}$/; //校验手机号
        if (re.test($('#personagePhone').val())) {
            $.get('/is_exist_mobile', {
                mobile: $('#personagePhone').val(),
            }, function (msg) {
                var jsonstr = JSON.stringify(msg)
                var result = eval('(' + jsonstr + ')')

                if (result['respcode'] == 1) {
                    //发送验证码

                    countdown($("#gainCode"));
                    $.get('/user/send_message', {
                        mobile: $('#personagePhone').val(),
                    }, function (msg) {


                    });
                    alert(result['detail'])
                } else {
                    alert(result['detail'])
                    $('#change_login').removeClass('pitch-bg')
                    $('#change_register').addClass('pitch-bg')
                    $('#login-index').css('display', 'none')
                    $('#register-index').css('display', 'block')
                    $(".auth-body-warp").show();
                }
            });
        }
        else {
            alert("请输入正确的手机号！")
        }
    })

    //注册验证码
    $('#register_gainCode').click(
        function () {
            if ($('#registerName').val() == ' ' || $('#registerName').val() == '') {
                alert('请填写姓名')
                return
            }
            var re = /^1[345678]\d{9}$/; //校验手机号
            if (re.test($('#registerPhone').val())) {
                //判断手机号是否注册过

                $.ajax({
                    type: "GET",
                    dataType: "json",
                    url: "/is_exist_mobile",//url
                    data: {mobile: $('#registerPhone').val()},
                    success: function (msg) {
                        var jsonstr = JSON.stringify(msg)
                        var result = eval('(' + jsonstr + ')')
                        if (result['respcode'] != 0) {
                            alert('该号码已注册！')
                            return
                        } else {
                            //发送验证码
                            countdown($("#register_gainCode"));
                            alert("验证码已发送，请注意查收")
                            $.get('/user/send_message', {
                                mobile: $('#registerPhone').val(),
                                principal: $('#registerName').val(),
                                company_name: $('#registerCompanyName').val(),
                                verification_code: $('#registerCode').val()
                            }, function (msg) {
                                regist_return_code = msg.detail
                                if (msg.msg == '提交成功') {
                                    countdown();
                                }
                            });
                        }
                    }
                })


            }
            else {
                alert("请输入正确的手机号！")
            }
        })

    //登录校验
    $('#loginButton').click(
        function () {
            var re = /^1[345678]\d{9}$/; //校验手机号
            if (re.test($('#personagePhone').val())) {
                $.ajax({
                    type: "POST",
                    dataType: "json",
                    url: "/mobile_login/",//url
                    data: {'mobile': $('#personagePhone').val(), 'code': $('#personageCode').val()},
                    success: function (data) {

                        var token_split = data.token.split('.')

                        token = token_split[1]
                        var str = Base64.decode(token);

                        setcookie("tooken", data.token)
                        refresh_page()
                    },
                    error: function (data) {
                        var response_text = eval('(' + data.responseText + ')');

                        alert(response_text.non_field_errors[0])
                    }
                })
            } else {
                alert("请输入正确的手机号！")
            }
        })

    //注册校验
    $('#registerButton').click(
        function () {

            var registerCompanyName = $("#registerCompanyName").val();
        var registerName = $("#registerName").val();
        var registerPhone = $("#registerPhone").val();
        var registerCode = $("#registerCode").val();
        if (registerCompanyName == '') {
            $("#registerCompanyName").css("border", "1px solid #ff7878")
            $("#registerCompanyName").next().css("opacity", "1");
        } else if (registerName == '') {
            $("#registerName").css("border", "1px solid #ff7878")
            $("#registerName").next().css("opacity", "1");
        } else if (registerPhone == '') {
            $("#registerPhone").css("border", "1px solid #ff7878")
            $("#registerPhone").next().css("opacity", "1");
        } else if (registerCode == '') {
            $("#registerCode").css("border", "1px solid #ff7878")
            $("#registerCode").next().css("opacity", "1");
        }

            var re = /^1[345678]\d{9}$/; //校验手机号

            if (re.test($('#registerPhone').val())) {
                //发送验证码
                $.get('/user/register', {
                    mobile: $('#registerPhone').val(),
                    principal: $('#registerName').val(),
                    company_name: $('#registerCompanyName').val(),
                    verification_code: $('#registerCode').val()
                }, function (msg) {
                    if (msg.detail == "注册成功！") {
                        $.ajax({
                            type: "POST",
                            dataType: "json",
                            url: "/mobile_login/",//url
                            data: {'mobile': $('#registerPhone').val(), 'code': $('#registerCode').val()},
                            success: function (data) {
                                var token_split = data.token.split('.')

                                token = token_split[1]

                                var str = Base64.decode(token);
                                setcookie("tooken", data.token)
                            }
                        })
                        alert(msg.detail)
                        refresh_page()
                    } else {
                        alert(msg.detail)
                    }
                });
            }
            else {
                alert("请输入正确的手机号！")
            }
        })
    //关闭按钮
    $('#close_btn').click(function () {
        $('.auth-body-warp').css('display', 'none')
    })


    //收藏页面
    $('#collect_page').click(function () {

        window.open("/collection")
    })
    //用户信息页面
    $('#user_page').click(function () {
        window.open("/user_page")
    })
    //订单页面
    $('#order_page').click(function () {
        window.open("/pay_order_page")
    })


    //登录
    $("#loginButton").click(function () {
        var personagePhone = $("#personagePhone").val();
        var personageCode = $("#personageCode").val();
        if (personagePhone == '') {
            $("#personagePhone").css("border", "1px solid #ff7878")
            $("#personagePhone").next().css("opacity", "1");
        } else if (personageCode == '') {
            $("#personageCode").css("border", "1px solid #ff7878")
            $("#personageCode").next().css("opacity", "1");
        }
    })



    //加载用户信息
    window.onload = function () {
        if (getCookie("tooken") != null && getCookie("tooken") != "null") {
            var token_split = getCookie("tooken").split('.')

            var payload = token_split[1]

            var str = Base64.decode(payload);


            var str1 = unescape(str.replace(/\\u/g, '%u'))

            var obj = JSON.parse(str1);
            $('#loginUl').css('display', 'none')
            $('#company_name').html(obj.company_name);
            $('#userList').css('display', 'block');

        }
    }

//退出登录响应事件
    $('#out').click(
        function () {
            delCookie("tooken")
            window.location.href = "/index"
        })
    $("#userList").click(function (e) {
        e.stopPropagation();
        $("#buttonList").slideToggle();
    })
    $(document).on("click", function (e) {

        $('#buttonList').slideUp();

    })


    $("#jsRegister div").click(function () {
        $("#jsRegister div").removeClass("pitch-bg");
        $(this).addClass("pitch-bg");

        if ($(this).index() == 0) {
            $("#login-index").css("display", "block");
            $("#register-index").css("display", "none");
        } else {
            $("#login-index").css("display", "none");
            $("#register-index").css("display", "block");
        }
    })
    //获取焦点
    $(".focus-input-border").focus(function () {
        $(this).css("border", "1px solid #71c977");
        $(this).next().css("opacity", "0");
    })
    //失去焦点
    $(".focus-input-border").blur(function () {
        $(this).css("border", "1px solid #dedede");
    })

})

//删除cookie
function delCookie(key) {

    var date = new Date();
    date.setTime(date.getTime() - 1);
    var delValue = getCookie(key);
    if (!!delValue) {
        document.cookie = key + '=' + null + ';expires=' + 0 + ";path=/";
        // document.cookie = key + '=' + null + ';expires=' + 0;
    }
}

function jumpad(url) {
    if (get_payLoad() == null) {
        alert("请先登录或注册！");
        $(".auth-body-warp").show();
        return
    }
    window.open(url);
}

//获取cookie信息
function getCookie(name) {
    var strcookie = document.cookie;//获取cookie字符串
    var arrcookie = strcookie.split("; ");//分割
    //遍历匹配
    for (var i = 0; i < arrcookie.length; i++) {
        var arr = arrcookie[i].split("=");
        if (arr[0] == name) {
            return arr[1];
        }
    }
    return "";
}

//设置cookie
function setcookie(name, value) {
    //设置名称为name,值为value的Cookie
    var expdate = new Date();   //初始化时间
    expdate.setTime(expdate.getTime() + 14 * 24 * 60 * 60000);   //时间
    document.cookie = name + "=" + value + ";expires=" + expdate.toGMTString() + ";path=/";
    // document.cookie = name + "=" + value + ";expires=" + expdate.toGMTString();
    //即document.cookie= name+"="+value+";path=/";   时间可以不要，但路径(path)必须要填写，因为JS的默认路径是当前页，如果不填，此cookie只在当前页面生效！~
}

//获取token信息
function get_payLoad() {
    if (getCookie("tooken") != "" && getCookie("tooken") != "null") {
        var token_split = getCookie("tooken").split('.')
        var payload = token_split[1]
        var str = Base64.decode(payload);
        var str1 = unescape(str.replace(/\\u/g, '%u'))
        var payLoad = JSON.parse(str1);
        return payLoad
    } else {
        return null
    }
}


//验证码计时
function countdown(obj) {
    var count = 60;
    $(obj).css({background: '#fff'}).val(count.toString() + "秒").attr('disabled', 'disabled');

    var doCount = function () {
        if (--count < 1) {
            var t2 = clearInterval(t1);
            $(obj).css({background: '#fff'}).val('重新发送').removeAttr('disabled');
        }
        else {
            $(obj).val(count.toString() + "秒");
        }
    };

    t1 = setInterval(function () {
        doCount();
    }, 1000);

}

function refresh_page() {
    window.location.reload();
}

//删除cookie
function delCookie(key) {
    var date = new Date();
    date.setTime(date.getTime() - 1);
    var delValue = getCookie(key);
    if (!!delValue) {
        document.cookie = key + '=' + null + ';expires=' + -1 + ";path=/";
        // document.cookie = key + '=' + null + ';expires=' + -1;
    }
}

//获取url请求参数
function GetRequest() {
    var url = location.search; //获取url中"?"符后的字串
    var theRequest = new Object();
    if (url.indexOf("?") != -1) {
        var str = url.substr(1);
        strs = str.split("&");
        for (var i = 0; i < strs.length; i++) {
            theRequest[strs[i].split("=")[0]] = unescape(strs[i].split("=")[1]);
        }
    }
    return theRequest;
}





